package com.kpf.springcloud.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kpf.springcloud.common.ResponseEnum;
import com.kpf.springcloud.exception.BusinessException;
import com.kpf.springcloud.mapper.TopicCommentMapper;
import com.kpf.springcloud.pojo.KpfTopic;
import com.kpf.springcloud.pojo.KpfTopicComment;
import com.kpf.springcloud.pojo.KpfUser;
import com.kpf.springcloud.pojo.PageResult;
import com.kpf.springcloud.service.IKpfTopicCommentService;
import com.kpf.springcloud.service.IKpfTopicService;
import com.kpf.springcloud.service.IKpfUserService;
import com.kpf.springcloud.service.ITokenService;
import com.kpf.springcloud.utils.GeneralUtil;
import com.kpf.springcloud.vo.CommentTopicVO;
import com.kpf.springcloud.vo.CommentUserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shiwen
 * @date 2021/3/10
 */
@Service
public class KpfTopicCommentServiceImpl extends BaseServiceImpl<TopicCommentMapper, KpfTopicComment> implements IKpfTopicCommentService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IKpfUserService userService;

    @Autowired
    private ITokenService tokenService;

    @Autowired
    private IKpfTopicService topicService;

    @Resource
    private TopicCommentMapper topicCommentMapper;

    @Override
    public void commentTopic(int topicId, String content) {
        String token = tokenService.verifyToken();
        if ("TOKEN_EXPIRED".equals(token)) {
            throw new BusinessException(ResponseEnum.TOKEN_EXPIRED);
        }
        int userId = Integer.parseInt(token.split("-")[0]);
        KpfTopicComment kpfTopicComment = KpfTopicComment.builder().userId(userId).topicId(topicId).commentStatus(0)
                .commentContent(content).build();
        save(kpfTopicComment);
        KpfTopic kpfTopic = topicService.getById(topicId);
        if (GeneralUtil.isObjNotNull(kpfTopic)) {
            kpfTopic.setCommentNum(kpfTopic.getCommentNum() + 1);
            // 原帖子的评论数 + 1
            topicService.update(topicService.getLambdaUpdateWrapper().eq(KpfTopic::getId, topicId).set(KpfTopic::getCommentNum, kpfTopic.getCommentNum()));
        }
    }

    /**
     * 根据帖子id获取所有的评论内容 - 分页
     *
     * @param topicId
     * @return
     */
    @Override
    public PageResult getCommentListByTopicId(int topicId, int pageNum, int pageSize) {
        Page<Object> page = PageHelper.startPage(pageNum, pageSize);
        List<KpfTopicComment> kpfTopicCommentList = list(getInitQueryWrapper().eq(KpfTopicComment::getTopicId, topicId)
                .eq(KpfTopicComment::getCommentStatus, 0));
        List<CommentTopicVO> commentTopicVOList = new ArrayList<>();
        // 这种写法很低效, 最好就是先查出集合再使用in来操作
        kpfTopicCommentList.forEach(s -> {
            KpfUser kpfUser = userService.getById(s.getUserId());
            CommentTopicVO commentTopicVO = new CommentTopicVO();
            commentTopicVO.setUserId(kpfUser.getId());
            commentTopicVO.setHeadimg(kpfUser.getHeadimg());
            commentTopicVO.setUsername(kpfUser.getUsername());
            commentTopicVO.setKpfTopicComment(s);
            commentTopicVOList.add(commentTopicVO);
        });
        return new PageResult(commentTopicVOList, page.getTotal(), pageNum, pageSize);
    }

    /**
     * 根据评论id删除评论内容
     *
     * @param commentId
     */
    @Override
    public void deleteCommentById(int commentId) {
        String token = tokenService.verifyToken();
        // 判断token是否过期
        if ("TOKEN_EXPIRED".equals(token)) {
            throw new BusinessException(ResponseEnum.TOKEN_EXPIRED);
        }
        // 用户id
        int userId = Integer.parseInt(token.split("-")[0]);
        // 角色类型
        int roleType = Integer.parseInt(token.split("-")[1]);
        // 管理员角色的type = 2
        if (roleType == 2) {
            KpfTopicComment topicComment = getById(commentId);
            topicCommentMapper.deleteById(commentId);
            KpfTopic kpfTopic = topicService.getById(topicComment.getTopicId());
            if (GeneralUtil.isObjNotNull(kpfTopic)) {
                kpfTopic.setCommentNum(kpfTopic.getCommentNum() - 1);
                // 原帖子的评论数 - 1
                topicService.update(topicService.getLambdaUpdateWrapper().eq(KpfTopic::getId, kpfTopic.getId())
                        .set(KpfTopic::getCommentNum, kpfTopic.getCommentNum()));
            }
            logger.info("Processing delete topic success！userId = {} , commentId = {}", userId, commentId);
        } else {
            throw new BusinessException(ResponseEnum.NOT_ADMIN_USER_TO_OPERA);
        }
    }

    /**
     * 分页获取所有的评论
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult getCommentList(int pageNum, int pageSize) {
        List<CommentUserVO> commentUserVOList = new ArrayList<>();
        Page page = PageHelper.startPage(pageNum, pageSize);
        List<KpfTopicComment> kpfTopicCommentList = list();
        kpfTopicCommentList.forEach(s -> {
            KpfUser kpfUser = userService.getById(s.getUserId());
            KpfTopic kpfTopic = topicService.getById(s.getTopicId());
            CommentUserVO commentUserVO = CommentUserVO.builder().commentContent(s.getCommentContent()).headimg(kpfUser.getHeadimg())
                    .id(s.getId()).title(kpfTopic.getTitle()).topicId(Long.parseLong(s.getTopicId() + ""))
                    .userId(Long.parseLong(s.getUserId() + "")).username(kpfUser.getUsername()).build();
            commentUserVOList.add(commentUserVO);
        });
        return new PageResult(commentUserVOList, page.getTotal(), pageNum, pageSize);
    }

}